﻿using System;
using System.Configuration;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace pic2box
{
  public partial class MainForm : Form
  {
    private static readonly string Folder = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["DropboxPublicFolder"]);
    private static readonly string LinkBase = ConfigurationManager.AppSettings["DropboxPublicUrlPrefix"];
    private static readonly int Timeout = int.Parse(ConfigurationManager.AppSettings["ClipboardPollingInterval"]);
    private static readonly string Format = ConfigurationManager.AppSettings["FileNameFormat"];
    private static readonly Timer Timer = StartTimer(DoWork);

    public MainForm()
    {
      InitializeComponent();

      // hide application
      this.Width = 0;
      this.Height = 0;      
    }

    // hide application #2
    private void Form1_Load(object sender, EventArgs e)
    {
      this.ShowInTaskbar = false;
      this.Hide();
    }

    private static void DoWork()
    {
      // is there any image in clipboard?
      var image = Clipboard.GetImage();
      if (image == null) return;

      // save pic to a public dropbox folder
      var name = string.Format(Format, Directory.GetFiles(Folder).Length);
      var path = Path.Combine(Folder, name);
      image.Save(path, ImageFormat.Png);

      // put a link of the file to the clipboard
      var hyperlink = LinkBase + name;
      Clipboard.SetText(hyperlink);
    }

    // create and start timer
    private static Timer StartTimer(Action doWork)
    {
      var timer = new Timer {Interval = Timeout};
      timer.Tick += (a,b) => doWork();
      timer.Start();
      return timer;
    }

    // pause/resume
    private void TrayClick(object sender, EventArgs e)
    {
      Timer.Enabled = !Timer.Enabled;
    }

    // exit
    private void TrayDoubleClick(object sender, EventArgs e)
    {
      this.Close();
    }
  }
}
